package framework.controller;

import framework.bo.SysUser;
import framework.common.ResponseVo;
import framework.service.SysUserRoleService;
import framework.service.SysUserService;
import framework.util._BeanUtil;
import framework.util.controller.BaseController;
import framework.util.http._HttpRequestUtil;
import framework.util.jdkExt._CollectionUtil;
import framework.util.shiro._ShiroUtil;
import framework.vo.SysRoleVo;
import frameworkExt.util.controller.BaseControllerExt;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.mgt.AuthenticatingSecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 吴宇亮 on 2019/2/23 0023 16:20
 */
@Controller
@RequestMapping("/framework/SysUser.do")
public class SysUserController extends BaseControllerExt {

    @Resource
    private SysUserService service;
    @Resource
    private SysUserRoleService sysUserRoleService;

    @ResponseBody
    @RequestMapping(params = "method=list")
    public ResponseVo list(ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        List<SysUser> list = service.list(_HttpRequestUtil.getRequestMap(request));
        for (SysUser sysUser : list) {
            List<SysRoleVo> sysRoleVoList = sysUserRoleService.getSysRoleVoByUserLid(sysUser.getLid())
                    .stream().filter(item -> item.getIsThisRole()).collect(Collectors.toList());
            try {
                sysUser.setRoleNames(_CollectionUtil.join(sysRoleVoList, SysRoleVo.CNAME, ","));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sendSuccess(list, service.getCount());
    }

    @ResponseBody
    @RequestMapping(params = "method=add")
    public ResponseVo add(HttpServletRequest request, SysUser bo){
        String rolelid = request.getParameter("rolelid");
        if(StringUtils.isBlank(rolelid)){
            return sendFail("参数错误");
        }
        bo.setPassword(_ShiroUtil.encodeSalt("123456", bo.getAccount()));
        setOperatorToBo(bo);
        service.add(bo, rolelid.split(","));
        return sendSuccess();
    }

    @ResponseBody
    @RequestMapping(params = "method=delete")
    public ResponseVo delete(ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        String lid = request.getParameter("lid");
        if (StringUtils.isBlank(lid)) {
            return sendFail("参数错误");
        }
        service.removeById(Integer.valueOf(lid));
        return sendSuccess();
    }

    @RequestMapping(params = "method=toEditOrDetail")
    public ModelAndView toEditOrDetail(ModelAndView model, HttpServletRequest request, HttpServletResponse response) {
        String lid = request.getParameter("lid");
        String pageUrl = request.getParameter("pageUrl");
        if(StringUtils.isAnyBlank(lid, pageUrl)){
            return null;
        }

        SysUser bo = service.get(Integer.valueOf(lid));
        model.addObject("bo", bo);
        model.addObject("roleList", sysUserRoleService.getSysRoleVoByUserLid(bo.getLid()));
        model.setViewName(pageUrl);
        return model;
    }

    @ResponseBody
    @RequestMapping(params = "method=update")
    public ResponseVo update(ModelAndView model, HttpServletRequest request, HttpServletResponse response){
        String lid = request.getParameter("lid");
        if(StringUtils.isBlank(lid)){
            return sendFail("参数错误");
        }

        try {
            service.update(request);
            return sendSuccess();
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error("", e);
            return sendError(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(params = "method=changePassword")
    public ResponseVo changePassword(@RequestParam String oldPassword, @RequestParam String newPassword, @RequestParam String comfirmNewPassword){
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(getCurrentUser().getAccount(), oldPassword);
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.login(token);
        } catch (AuthenticationException e) {
            return sendFail("旧密码错误");
        }

        if(!StringUtils.equals(newPassword, comfirmNewPassword)){
            return sendFail("新的密码 和 确认密码 不一致");
        }

        SysUser sysUser = service.get(getCurrentUser().getLid());
        String password = _ShiroUtil.encodeSalt(newPassword, getCurrentUser().getAccount());
        sysUser.setPassword(password);
        service.update(sysUser);
        return sendSuccess();
    }

}
